package com.icinfo.cloud.provider.common.crontask;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.SMSUtils;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.vo.ZfAndManageUserInfoVO;
import com.icinfo.cloud.provider.punish.common.systemmessage.dto.SystemMessageInsertDto;
import com.icinfo.cloud.provider.punish.common.systemmessage.service.ICaseSystemMessageService;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseHandlePersonRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseReasonMainRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 钉钉通知消息
 */
@Component
public class DingNoticeTask {

    @Resource
    CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    ICasePartiesRecordService casePartiesRecordService;
    @Resource
    CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;
    @Resource
    CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    CaseSourceRegisterMainInfoMapper caseSourceRegisterMainInfoMapper;
    @Resource
    IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    ICaseSystemMessageService caseSystemMessageService;
    @Value("${ding.sendUrl}")
    private String dingSendUrl;
    /**
     * 案件到期提前提示
     */
    @Scheduled(cron = "30 55 20 * * ?")
    public void ajdqts() {
        System.out.println("案件到期提前提示");
        List<Map<String,String>> expireList =  caseMainInfoMapper.selectSevExpireCase();
        if(expireList==null||expireList.size()==0){
            return;
        }
        for(int i=0;i<expireList.size();i++){
            Map<String,String> map = expireList.get(i);
            String caseId = map.get("caseid");
            String expireTime = map.get("casetimelimit");
            String caseNumber = map.get("casenumber");
            Example reasonExample = new Example(CaseReasonMainRecord.class);
            reasonExample.createCriteria().andEqualTo("caseId",caseId);
            CaseReasonMainRecord reasonMainRecord = caseReasonMainRecordMapper.selectByExample(reasonExample).get(0);
            List<CasePartiesRecordVo> partiesRecordList = casePartiesRecordService.getCasePartiesInfo(caseId);
            CasePartiesRecordVo partiesRecord = partiesRecordList.get(Constant.INTEGER_0);
            //办案人
            Example handleExample = new Example(CaseHandlePersonRecord.class);
            handleExample.createCriteria().andEqualTo("caseId",caseId).andEqualTo("status",Constant.STRING_1);
            List<CaseHandlePersonRecord> handleList = caseHandlePersonRecordMapper.selectByExample(handleExample);
            if(handleList!=null&&handleList.size()>0){
                for(CaseHandlePersonRecord record :handleList){
                    if(StringUtils.isNotEmpty(record.getDingId())){
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("caseId", caseId);
                        jsonObject.put("caseNumber", caseNumber);
                        jsonObject.put("expireTime", expireTime);
                        jsonObject.put("dingDingId", record.getDingId());
                        jsonObject.put("handlePersonName", record.getHandlePersonName());
                        jsonObject.put("partyName",partiesRecord.getPartyName());
                        jsonObject.put("url","");
                        jsonObject.put("caseReasonName",reasonMainRecord.getCaseReasonName());
                        jsonObject.put("dingMsgType","caseDue");
                        BaseUtil.post(dingSendUrl, jsonObject);
                        //DingDingUtil.expireMsg(caseId,null,caseNumber,expireTime,record.getDingId(),record.getHandlePersonName()
                                //,partiesRecord.getPartyName(),reasonMainRecord.getCaseReasonName(),"");

                        //工作台-消息提醒
                        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
                        String title = "案件到期提示";
                        String msg = "您编号【" + caseNumber + "】的案件将在" + expireTime + "后过期，请尽快处理。\n\n"
                                + "当事人：" + partiesRecord.getPartyName() + "\n\n"
                                + "案由：" + reasonMainRecord.getCaseReasonName();
                        SystemMessageInsertDto dto = new SystemMessageInsertDto();
                        dto.setContent(msg);
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("caseId", caseId);
                        paramMap.put("caseCurrentStageName", caseMainInfo.getCaseCurrentStageName());
                        paramMap.put("dataSource", null);
                        String json = JSON.toJSONString(paramMap, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.QuoteFieldNames);
                        dto.setParamsJson(json);
                        dto.setReceiverDept(record.getHandleOrgCode());
                        dto.setReceiverId(record.getHandlePersonId());
                        dto.setTitle(title);
                        dto.setType("4");
                        caseSystemMessageService.insertSystemMessage(dto);
                    }
                }
            }
        }
    }

    /**
     * 文书送达提前提示
     */
    @Scheduled(cron = "30 46 21 * * ?")
    public void wssdts() {
        System.out.println("----文书送达提前提示--------");
        List<Map<String,String>> expireList = caseDocumentRecordMapper.selectExpireDoc();
        if(expireList==null||expireList.size()==0){
            return;
        }
        for(int i=0;i<expireList.size();i++){
            Map<String,String> map = expireList.get(i);
            String caseId = map.get("caseid");
            String partyname = map.get("partyname");
            String doccode = map.get("doccode");
            String docnum = map.get("docnum");
            String docname = map.get("docname");

            //办案人
            Example handleExample = new Example(CaseHandlePersonRecord.class);
            handleExample.createCriteria().andEqualTo("caseId",caseId).andEqualTo("status",Constant.STRING_1);
            List<CaseHandlePersonRecord> handleList = caseHandlePersonRecordMapper.selectByExample(handleExample);
            if(handleList!=null&&handleList.size()>0){
                for(CaseHandlePersonRecord record :handleList){
                    if(StringUtils.isNotEmpty(record.getDingId())){
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("caseId", caseId);
                        jsonObject.put("docCode", doccode);
                        jsonObject.put("docNum", docnum);
                        jsonObject.put("dingDingId", record.getDingId());
                        jsonObject.put("handlePersonName", record.getHandlePersonName());
                        jsonObject.put("partyName",partyname);
                        jsonObject.put("url","");
                        jsonObject.put("docName",docname);
                        jsonObject.put("dingMsgType","docSendCue");
                        BaseUtil.post(dingSendUrl, jsonObject);
                        //DingDingUtil.wsMomentMsg(caseId,doccode,docnum,partyname,record.getDingId(),record.getHandlePersonName(),docname
                        //,"");

                        //工作台-消息提醒
                        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
                        String title = "文书送达临期提示";
                        String msg = "您编号【" + docnum + "】的文书即将送达超期。"
                                + "\n\n当事人：" + partyname
                                + "\n\n文书类型：" + record.getHandlePersonName();
                        SystemMessageInsertDto dto = new SystemMessageInsertDto();
                        dto.setContent(msg);
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("caseId", caseId);
                        paramMap.put("caseCurrentStageName", caseMainInfo.getCaseCurrentStageName());
                        paramMap.put("dataSource", null);
                        String json = JSON.toJSONString(paramMap, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.QuoteFieldNames);
                        dto.setParamsJson(json);
                        dto.setReceiverDept(record.getHandleOrgCode());
                        dto.setReceiverId(record.getHandlePersonId());
                        dto.setTitle(title);
                        dto.setType("7");
                        caseSystemMessageService.insertSystemMessage(dto);
                    }
                }
            }
        }
    }


    /**
     * 案源处置过期前一天预警提醒（短信+ding）
     */
    //@Scheduled(cron = "0 0 24 * * ?")
    public void ayczyjts() {
        System.out.println("案源处置过期前一天预警提醒");
        List<Map<String,String>> aYWarningList =  caseSourceRegisterMainInfoMapper.selectAYWarning();
        if(aYWarningList == null || aYWarningList.size() == 0){
            return;
        }
        Map<String,String> map;
        List<String> afterUserIdList;
        for(int i=0;i<aYWarningList.size();i++){
            map = aYWarningList.get(i);
            afterUserIdList = new ArrayList<>();
            // 办案机构名称
            String handleOrgName = map.get("handleOrgName");
            // 案源编号
            String taskNum = map.get("taskNum");
            // 处置日期
            String termTime = map.get("termTime");
            // 主办人id
            afterUserIdList.add(map.get("personMainId"));
            // 协办人id
            afterUserIdList.add(map.get("personAssistId"));
            List<ZfAndManageUserInfoVO> zfAndManageUserInfoVoList = xzzfInterfaceService.getZfAndManageUsersByUserIds(afterUserIdList);
            if (CollectionUtils.isNotEmpty(zfAndManageUserInfoVoList) && zfAndManageUserInfoVoList.size() > 0){
                for (ZfAndManageUserInfoVO user : zfAndManageUserInfoVoList) {
                    try {
                        // 发送短信
                        String msg = "【" + handleOrgName + "】案源处置过期通知。" + user.getRealName() + "，你好。你承办的案源【" + taskNum + "】将于1个工作日后处置过期（截止" + termTime + ")，请及时处置。处置路径:处罚办案系统-案源中心-我的案源。";
                        SMSUtils.sendTextMessage(user.getPhone(), msg,"");
                        // 发送ding消息
                        if(StringUtils.isNotEmpty(user.getDingDingId())){
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("dingDingId", user.getDingDingId());
                            jsonObject.put("caseNumber",taskNum);
                            jsonObject.put("expireTime",termTime);
                            jsonObject.put("dingMsgType","caseSourceWarning");
                            BaseUtil.post(dingSendUrl, jsonObject);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
